package com.wtp.wallpaper;

import com.wtp.wallpaper.annotation.ScheduledAnnotation;
import com.wtp.wallpaper.pojo.entity.ScheduledTime;
import com.wtp.wallpaper.service.ScheduledService;
import com.wtp.wallpaper.utils.TaskSchedulerUtil;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;


import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Component
public class AppInitializer {
    @Autowired
    private ApplicationContext context;
    @Autowired
    private ScheduledService scheduledService;
    @EventListener(ContextRefreshedEvent.class)
    public void initAfterIoc() {

        log.info("初始化完成,开始进行自动配置");

        List<ScheduledTime> list = new ArrayList<>();
        Reflections reflections = new Reflections("com.wtp.wallpaper.task");
        Set<Class<? extends Runnable>> takes = reflections.getSubTypesOf(Runnable.class);
        //获取到所有定时任务,将所有定时任务注册
        takes.forEach(clazz -> {
            // 获取类上的指定注解
            if (clazz.isAnnotationPresent(ScheduledAnnotation.class)) {
                ScheduledAnnotation annotation = clazz.getAnnotation(ScheduledAnnotation.class);

                Runnable task = context.getBean(clazz);

                TaskSchedulerUtil.put(task, new CronTrigger(annotation.cron())
                        , clazz.getName());

                ScheduledTime scheduledTime = ScheduledTime.builder()
                        .id(clazz.getName())
                        .scheduledName(annotation.value())
                        .cron(annotation.cron())
                        .description(annotation.description())
                        .state(1)
                        .build();
                list.add(scheduledTime);
            }
        });

        if(!list.isEmpty()) {
            log.info("根据注解更新数据库");
            scheduledService.saveOrUpdateBatch(list);
        }
        log.info("定时任务注册完成");
    }
}